package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"xdingtec.cn/xdkaika/app"
	"xdingtec.cn/xdkaika/app/http/api/service"
	form "xdingtec.cn/xdkaika/app/http/api/validator/wechat"
	"xdingtec.cn/xdkaika/app/models"
	"xdingtec.cn/xdkaika/utils/jwt"
	"xdingtec.cn/xdkaika/utils/jwt/claims"
	"xdingtec.cn/xdkaika/utils/response"
	"xdingtec.cn/xdkaika/utils/wechat"
)

type WechatController struct {
}

// @author      mz100
// @description 登录
// @param
// @return
func (w *WechatController) Login(c *gin.Context) {
	var f form.LoginForm
	if err := c.ShouldBind(&f); err != nil {
		response.ValidatorError(c, err)
		return
	}
	// 获取实例
	wechat := wechat.GetMiniProgram()
	auth := wechat.GetAuth()
	// 验证小程序
	_, err := auth.Code2Session(f.Code)
	err = nil
	if err != nil {
		response.ErrorSystem(c, "小程序获取session失败", gin.H{"error": err.Error()})
		return
	}
	openid := "xxxxxxxxxxxxxx"
	us := &service.UserService{}
	user, err := us.GetByOpenId(openid)
	// 新增用户
	if err != nil || user == nil {
		u := &models.UserModel{}
		u.OpenId = openid
		u.UUID = uuid.New()
		user, err := us.Create(u)
		if err != nil || user == nil {
			response.ErrorSystem(c, "新增用户失败", gin.H{"error": err.Error()})
			return
		}
	}
	claims := &claims.JWTClaims{
		OpenId:   user.OpenId,
		UserId:   user.ID,
		Username: user.Username,
	}
	token, err := jwt.GenerateToken(claims)
	if err != nil {
		response.ErrorSystem(c, "token生成失败", gin.H{"error": err.Error()})
		return
	}

	response.Success(c, "", gin.H{"token": token})

}

// @author      mz100
// @description 退出
// @param
// @return
func (w *WechatController) Logout(c *gin.Context) {

	if app.JWTClaims != nil {
		_, err := jwt.DeleteToken(app.JWTClaims)
		if err != nil {
			response.ErrorSystem(c, "token清理失败", gin.H{"error": err.Error()})
			return
		}
	}

	response.Success(c, "", gin.H{})
}
